<template>
  <div class="app-container">
    <h1 style="text-align: center">员工信息统计</h1>
    <div ref="chart" style="width: 100%; height: 500px;"></div>
  </div>
</template>

<script>
import { page as getEmpList } from '@/api/emp.js'
import { findAll as getDeptList } from '@/api/dept.js'
import * as echarts from 'echarts'

export default {
  data() {
    return {
      chart: null,
      deptList: [],
      empList: []
    }
  },
  mounted() {
    this.initChart()
    this.fetchData()
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
    },
    async fetchData() {
      try {
        // 获取部门列表
        const deptRes = await getDeptList()
        this.deptList = deptRes.data.data || []

        // 获取员工列表，这里假设后端支持获取所有员工，可按需调整参数
        const empRes = await getEmpList('', '', '', '', 1, 9999)
        this.empList = empRes.data.data.rows || []

        this.renderChart()
      } catch (error) {
        console.error('获取数据失败:', error)
      }
    },
    renderChart() {
      // 按部门统计员工数量
      const deptEmpCount = this.deptList.map(dept => {
        const count = this.empList.filter(emp => emp.dept_id === dept.id).length
        return {
          value: count,
          name: dept.name
        }
      })

      // 过滤掉员工数量为 0 的部门
      const filteredDeptEmpCount = deptEmpCount.filter(item => item.value > 0)

      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '员工数量',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: filteredDeptEmpCount
          }
        ]
      }

      this.chart.setOption(option)

      // 监听窗口大小变化，重新调整图表大小
      window.addEventListener('resize', () => {
        this.chart.resize()
      })
    }
  },
  beforeDestroy() {
    if (this.chart) {
      window.removeEventListener('resize', () => {
        this.chart.resize()
      })
      this.chart.dispose()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
